# -*- coding: utf-8 -*-
 
import platform
import os
import time
import threading
import socket
import subprocess


def get_os():
    os = platform.system()
    if os == "Windows":
        return "n"
    else:
        return "c"
 
live_ip = 0
ip = [] 
def ping_ip(ip_str):
    cmd = ["ping", "-{op}".format(op=get_os()),
           "1", ip_str]
    output = os.popen(" ".join(cmd)).readlines()
    for line in output:
        if str(line).upper().find("TTL") >= 0:
            print("ip: %s 在线" % ip_str)
            global live_ip
            global ip
            ip.append(ip_str)
            live_ip += 1
            break
 
 
def find_ip(ip_prefix):
    '''''
    给出当前的ip地址段 ，然后扫描整个段所有地址
    '''
    threads = []
    for i in range(1, 256):
        ip = '%s.%s' % (ip_prefix, i)
        threads.append(threading.Thread(target=ping_ip, args={ip, }))
    for i in threads:
        i.start()
    for i in threads:
        i.join()
 
 
def find_local_ip():
    """
    获取本机当前eth0 ip地址
    :return: 返回本机ip地址
    """
    result = subprocess.run(['ifconfig', 'eth0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode == 0:
        output = result.stdout.decode()
        ip = output.split('\n')[1].split()[1]
        mask = output.split('\n')[3].split()[1]
        gateway = output.split('\n')[5].split()[1]
        print("本机eth0 ip:",ip)
        
    else:
        ip = "192.168.1.3"
        raise Exception('获取eth0信息失败')
    
    return ip
 
 
if __name__ == "__main__":
    print("开始扫描时间: %s" % time.ctime())
    addr = find_local_ip()
    args = "".join(addr)
    ip_pre = '.'.join(args.split('.')[:-1])
    find_ip(ip_pre)
    ip.remove(addr)
    with open("ip.txt","w+") as f:
    	for i in range(0, len(ip)):
		    f.write(f"{ip[i]}\n")
	
    print("扫描结束时间 %s" % time.ctime())
    print('本次扫描共检测到本网络存在%s台设备' % live_ip)

 
